import { code } from '@/config';
import { Message, Loading } from 'element-ui';
import { request } from './request';

/** 接口成功或失败的提示 */
const notify = {
  onFulfilled: (response) => {
    console.log('打印***response', response);
    const res = response.data;
    const { desc } = response.config;
    // 如果desc被定义，则执行反馈逻辑
    // 判断code码 200是成功
    if (res.code === code && response.data) {
      // 判断是否需要显示
      if (desc) {
        Message({
          type: 'success',
          message: desc,
        });
      }
    } else {
      Message({
        type: 'error',
        message: res.errorDesc || '接口处理异常',
      });
    }
  },
  onRejected: (error) => {
    const { response, config } = error;
    // 对4xx，5xx状态码做失败反馈
    const { url } = config;
    if (response?.status && response?.statusText) {
      Message({
        type: 'error',
        message: `状态：${response.status}~${response.statusText}
                  路径：${url}`,
      });
    } else {
      // 处理请求响应失败,例如网络offline，超时等做失败反馈
      Message({
        type: 'error',
        message: '接口无响应',
      });
    }
  },
};

let loadingInstance;
const baseConfig = {
  baseURL: process.env.VUE_APP_API,
  timeout: 1000 * 10,
  interceptors: {
    // 添加请求头
    requestInterceptor: (config) => {
      console.log('打印***config', config);
      const { loadingOption } = config;
      const defaultLoadingOption = {
        text: '拼命加载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.8)',
      };
      if (loadingOption) {
        loadingInstance = Loading.service(
          loadingOption === true ? defaultLoadingOption : loadingOption,
        );
      }

      return config;
    },
    requestInterceptorCatch: (error) => Promise.reject(error),
    responseInterceptor: (response) => {
      // 添加提示
      notify.onFulfilled(response);
      loadingInstance.close();
      return response.data;
    },
    responseInterceptorCatch: (error) => {
      // 错误提示
      notify.onRejected(error);
      return Promise.reject(error);
    },
  },
};

export default request(baseConfig);
